﻿CREATE PROCEDURE [dbo].[ArticleSales_SelectByRangeReview]
	@RangeReviewId int,
	@CategoryId int
AS
	  SELECT 
	  cat.Name Category, 
	  subcat.Name Subcategory,
	  st.Name StoreName, 
	  a.Name ArticleName, 
	  a.Code ArticleCode, 
	  a.UOM UOM,
	  s.*
	  FROM ArticleSales s
	  INNER JOIN Articles a on s.ArticleId = a.Id
	  INNER JOIN Stores st on s.StoreId= st.Id
	  INNER JOIN Categories subcat on a.CategoryId = subcat.Id
	  INNER JOIN Categories cat on subcat.ParentId = cat.Id
	  WHERE 
			a.RangeReviewId = @RangeReviewId
		AND @CategoryId = 0 OR (subcat.Id = @CategoryId or subcat.ParentId = @CategoryId)
	  ORDER BY cat.Name, subcat.Name, st.Name, a.Name
RETURN 0